<template>
  <div class="wrapper">
    <el-form v-loading="formLoading" ref="form" label-width="116px" :model="inputForm">
      <el-row class="panel">
        <el-form-item :label="customType + '名称:'" required>
          <el-input  @focus="getCustom" :placeholder="'请选择'+customType" v-model="inputForm.companyName"></el-input>
        </el-form-item>
        <el-form-item label="数据类别:" required>
          <el-select size="small" v-model="inputForm.dataType" placeholder="请选择">
            <el-option v-for="item in   $dictUtils.getDictList('dataType')" :key="item.value"
                       :label="item.label"
                       :value="Number(item.value)">
            </el-option>
          </el-select>
<!--          <el-checkbox >承担运费</el-checkbox>-->
        </el-form-item>
      </el-row>
      <el-row class="panel">
        <el-form-item :label="productType + '名称:'" required>
          <el-input @focus="getProduct" :placeholder="'请选择'+productType" v-model="inputForm.productName"></el-input>
        </el-form-item>
          <el-row class="contact-container">
            <el-form-item :label="productType+'单价:'" prop="payMode" required>
              <el-select size="small" v-model="inputForm.payMode" placeholder="请选择">
                <el-option v-for="item in   $dictUtils.getDictList('payMode')" :key="item.value"
                           :label="item.label"
                           :value="Number(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="0" prop="price" :rules="[
              {validator:validator.isNumber, trigger:'blur'},
            ]">
              <el-input @input="(e)=>checkInput(e,'price')" class="adjustInputAppend"  clearable v-model="inputForm.consumeRatio"
                        placeholder="请输入单价" v-filter-special-char="inputForm.price">
                <span slot="suffix">吨/车</span>
              </el-input>
            </el-form-item>
            <el-checkbox v-model="inputForm.isFreight">含运费</el-checkbox>
          </el-row>
      </el-row>
      <el-row class="panel">
        <el-form-item label="数量:" required>
          <el-input placeholder="请输入数量" class="adjustInputAppend" v-model="inputForm.quantity">
            <span slot="suffix" class="">吨</span>
          </el-input>
        </el-form-item>
        <el-form-item label="金额:" required>
          <el-input placeholder="请输入金额" class="adjustInputAppend" v-model="inputForm.smoney">
            <span slot="suffix" class="">元</span>
          </el-input>
        </el-form-item>
      </el-row>
      <el-row class="panel">
        <el-row class="contact-container compute">
          <el-form-item label="亏吨标准:" prop="computeMethod">
            <el-select clearable v-model="inputForm.computeMethod">
              <el-option
                v-for="item in  $dictUtils.getDictList('calcType')"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label-width="0" prop="allowLossQuantity" :rules="[
              {validator:validator.isNumber, trigger:'blur'},
              {validator:checkConsumeRatio, trigger:'blur'}
            ]" v-show="inputForm.computeMethod===Number($dictUtils.getDictList('calcType')[0].value)">
            <el-input class="adjustInputAppend" placeholder="请输入亏吨" v-model="inputForm.allowLossQuantity">
              <span slot="suffix">吨/车</span>
            </el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="allowLossPercent" :rules="[
              {validator:validator.isNumber, trigger:'blur'},
              {validator:checkConsumePer, trigger:'blur'}
            ]" v-show="inputForm.computeMethod===Number($dictUtils.getDictList('calcType')[1].value)">

            <el-input class="adjustInputAppend appendLess inputBox" placeholder="请输入亏吨百分比" v-model="inputForm.allowLossPercent">
              <span slot="suffix">%</span>
            </el-input>

          </el-form-item>
          <el-form-item label-width="0" v-show="inputForm.computeMethod===Number($dictUtils.getDictList('calcType')[2].value)">
            <div class="number-wrapper random">
              <div>
                <el-form-item prop='randomLower' :rules="[
                  {required: true, message:'请输入随机数下限', trigger:'blur'},
                  {validator: validator.isFloat, trigger:'blur'}
                 ]" >
                  <el-input-number v-model="inputForm.randomLower" :min="0.00" controls-position="right" size="mini" :precision="2" :step="1" ></el-input-number>
                </el-form-item>
              </div>
              <div class="line" style="margin: 0 10px">～</div>
              <div>
                <el-form-item prop='randomUpper' :rules="[
                  {required: true, message:'请输入随机数上限', trigger:'blur'},
                  {validator: validator.isFloat, trigger:'blur'}
                 ]">
                  <el-input-number v-model="inputForm.randomUpper" :min="0.00"  controls-position="right" size="mini" :precision="2" :step="1" ></el-input-number>
                </el-form-item>
              </div>
            </div>
          </el-form-item>
        </el-row>
        <el-form-item label="合同编号:" required>
          <el-input placeholder="请输入正式合同编号" v-model="inputForm.contractCode"></el-input>
        </el-form-item>
      </el-row>
      <el-row class="panel">
        <el-form-item :label="accountType+'账户:'" prop="account" required>
          <el-select size="small" v-model="inputForm.account" placeholder="请选择">
            <el-option v-for="item in   $dictUtils.getDictList('financeAccountType')" :key="item.value"
                       :label="item.label"
                       :value="Number(item.value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="addressType+'地点:'"
                      :rules="[{ required: true, message: '请输入+'+addressType+'地点', trigger: 'change' }]">
          <!--            <el-input clearable placeholder="请填写收货单位" v-model="inputForm.receiveCompanyName" v-filter-special-char="inputForm.receiveCompanyName"></el-input>-->
          <el-autocomplete :placeholder="'请填写'+addressType+'地点'" class="adjustPopper"
                           :debounce="0" :fetch-suggestions="querySearch" @select="handleSelect($event)"
                           :trigger-on-focus="true" @change="setAddress('receive')"
                           v-model="inputForm.companyAddressName" @keydown.native="keydown($event)" clearable>
            <template slot-scope="{ item }">
              <section class="querySearch-autocomplete">
                <section class="name-item" v-if="item.addressName !== ''">
                  <section class="name"><span v-if="item.id">{{ item.addressName.substr(0,1) }}</span></section>
                  {{item.addressName}}
                </section>
                <section>
                </section>
              </section>
              <div></div>
            </template>
          </el-autocomplete>
        </el-form-item>
      </el-row>
      <el-row class="panel">
        <el-form-item label="执行开始时间:">
<!--                      :rules="[-->
<!--                          {validator:checkSendDate, trigger:'blur'}-->
<!--                          ]"-->
          <el-date-picker class="adjustDate" v-model="sendDate" type="daterange"
                          value-format="yyyy-MM-dd" range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          format="yyyy-MM-dd"
                          align="right">
          </el-date-picker>
        </el-form-item>
      </el-row>
      <div class="remark">
        <el-form-item label="备注:">
          <el-input type="textarea" class="adjustTextArea" v-model="inputForm.remark" maxlength="200" show-word-limit
                    v-filter-special-char="inputForm.remark" placeholder="请输入">
          </el-input>
        </el-form-item>
      </div>
      <el-row class="panel">
        <el-form-item label="相关附件">
          <el-upload class="upload-demo" :action="$http.BASE_URL + '/business/fileUpload'"
                     :headers="{ token: $cookie.get('token'),  dbNameSys: dpName}"
                     :on-remove="handleRemove" :on-success="hanleSuccess" :before-remove="beforeRemove"
                     v-model="inputForm.contractFileId"
                     multiple :limit="3" :file-list="fileList">
            <el-button size="small" type="default">点击上传</el-button><span slot="tip" class="el-upload__tip">文件不能超过500kb</span>
          </el-upload>
        </el-form-item>
      </el-row>



    </el-form>
    <div class="text_center">
      <div>
        <el-button type="primary" :disabled="saveLoading" class="btn_next"
                   @click="submit">确定
        </el-button>
        <el-button class="btn_cancel" :disabled="saveLoading"  @click="close">取消</el-button>
      </div>
    </div>
<!--    <chooseCustomer ref="chooseCustomer"></chooseCustomer>-->
    <companyDialog ref="companyDialog" @getCompanyData="getCompanyData"></companyDialog>
    <productDialog ref="productDialog" placeholder="请输入产品名称" @getProductData="getProductData"></productDialog>
  </div>

</template>

<script>
// import chooseCustomer from './chooseCustomer'
import companyDialog from '@/components/dialog/companyDialog'
import productDialog from '@/components/dialog/productDialog.vue'
import { postModelPage } from '@/api/model/model.js'
import { getLocalStorage } from '@/utils/localstore.js'
export default {
  name: 'businessFormModel1',
  components: {
    // chooseCustomer,
    companyDialog,
    productDialog
  },
  props: ['processType'],
  data () {
    return {
      formLoading: false,
      sendDate: [],
      fileList: [],
      dpName: '',
      contractFileIdArr: [],
      saveLoading: false,
      customType: '',
      productType: '',
      accountType: '',
      addressType: '',
      inputForm: {
        modelId: '',
        modelName: '',
        companyName: '',
        companyId: '',
        dataType: '',
        // 用于产品S
        isFreight: false,
        price: '',
        productId: '',
        productName: '',
        payMode: '',
        // 用于产品E
        quantity: '',
        smoney: '',
        computeMethod: '',
        allowLossQuantity: '',
        allowLossPercent: '',
        randomLower: '',
        randomUpper: '',
        account: '',
        contractCode: '',
        executeStartDate: '',
        executeEndDate: '',
        contractFileId: '',
        companyAddressName: '',
        companyAddressId: '',
        remark: '',
      }
    }
  },
  watch: {
    'inputForm.computeMethod' (val) {
      this.inputForm.allowLossQuantity = ''
      this.inputForm.allowLossPercent = ''
      this.inputForm.randomUpper = ''
      this.inputForm.randomLower = ''
    }
  },
  computed: {
    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs
      },
      set(val) {
        this.$store.commit('common/updateMainTabs', val)
      }
    },
    mainTabsActiveName: {
      get() {
        return this.$store.state.common.mainTabsActiveName
      },
      set(val) {
        this.$store.commit('common/updateMainTabsActiveName', val)
      }
    },
  },
  mounted () {
    this.dpName = getLocalStorage('tenantCode')
    this.inputForm.modelId = this.$route.query.id
    this.inputForm.modelName = this.$route.query.title
    if (this.processType == 1) {
      this.customType = '客户'
      this.productType = '产品'
      this.accountType = '发货'
      this.addressType = '收货'
    } else if (this.processType == 2) {
      this.customType = '供应商'
      this.productType = '原料'
      this.accountType = '收货'
      this.addressType = '发货'
    }
  },
  methods: {
    getCustom () {
      this.$refs.companyDialog.initData()
    },
    getProduct () {
      this.$refs.productDialog.init()
    },
    getProductData (row) {
      this.inputForm.productName = row.name
      this.inputForm.productId = row.id
    },
    handleSelect ($event) {
        this.inputForm.companyAddressName = $event.addressName
        this.inputForm.companyAddressId = $event.id
    },
    keydown (e) {
      if (e.keyCode === 32) {
        e.returnValue = false
      }
    },
    // 小数点后两位
    limitDecimals (value) {
      const reg = /^(\-)*(\d+)\.(\d\d).*$/
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
      } else {
        return ''
      }
    },
    // @input
    checkInput (val, name) {
      let value = this.limitDecimals(val)
      this.$nextTick(() => {
        this.$set(this.inputForm, name, value)
      })
    },
    // 客户选择数据回显
    getCompanyData (row) {
      this.inputForm.companyName = row.names
      this.$set(this.inputForm, 'companyId', row.id)
    },
    // 检测途耗
    checkConsumeRatio(rule, value, callback) {
      if (value < 0) {
        callback(new Error('亏吨固定值不能小于0'))
      } else {
        if (value > 1) {
          callback(new Error('亏吨固定值不能超过1'))
        } else {
          callback()
        }
      }
    },
    checkConsumePer(rule, value, callback) {
      if (value < 0) {
        callback(new Error('亏吨百分比不能小于0'))
      } else {
        if (value > 100) {
          callback(new Error('亏吨百分比不能超过100'))
        } else {
          callback()
        }
      }
    },
    // 上传移除
    handleRemove (file, fileList) {
      this.fileList = fileList
      console.log(this.fileList)
      // deleteFile()
      // splice
    },

    // 上传成功
    hanleSuccess (response, file, fileList) {
      this.contractFileIdArr.push(response.result.id)
      this.fileList = fileList
    },
    // 上传移除前
    beforeRemove (file) {
      // for (let i = 0; i < this.fileList.length; i++) {
      //   if (file.uid === this.fileList[i].uid) {
      //     for (let index = 0; index < this.types.length; index++) {
      //       if (this.types[index].itemFormat === 'upload') {
      //         let key = this.types[index].pageKey
      //         deleteFile({
      //           oleImgId: this.form.form[key][i]
      //         }).then(res => {
      //           this.form.form[key].splice(i, 1)
      //         })
      //       }
      //     }
      //   }
      // }
    },

    querySearch (queryString, cb) {
      if (this.inputForm.companyId === '') {
        // alert('请先选择客户')
        return
      }
      this.$http({
        url: '/basis/sales/companyAddress/findAddressByKeyword',
        method: 'get',
        params: {
          companyId: this.inputForm.companyId,
          keyWord: queryString
        }
      }).then((res) => {
        if (res.data.code === '200') {
          this.values = []
          for (let index = 0; index < res.data.result.length; index++) {
            let element = {
              id: '',
              addressName: '',
            }
            element.id = res.data.result[index].id
            if (res.data.result[index].addressName !== undefined) {
              element.addressName = res.data.result[index].addressName
            } else if (res.data.result[index].detailAddress !==undefined) {
              element.addressName = res.data.result[index].detailAddress
            }
            this.values.push(element)
          }
          cb(this.values)// 返回搜索下拉框里面数据
        }
      })
      // 调用 callback 返回建议列表的数据
    },
    // 验证发运期间
    checkSendDate (rule, value, callback) {
      let stratStr = value[0] + ':00:00'
      let currentTime = Date.now()
      let compareTime = currentTime - 1 * 60 * 60 * 1000  // 当前小时的时间也可选，所以把要比较的时间戳提前一小时
      const startData = new Date(stratStr)
      const time = startData.getTime()
      if (time <= compareTime) {
        callback(new Error('开始时间不能小于当前时间'))
      } else {
        if (value[0] === value[1]) {
          callback(new Error('开始时间不能与结束时间相同'))
        } else {
          callback()
        }
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          let product = {
            isFreight: this.inputForm.isFreight === true ? 1 : 0,
            price: this.inputForm.price,
            productId: this.inputForm.productId,
            productName: this.inputForm.productName,
            payMode: this.inputForm.payMode
          }

          let params = {
            modelId: this.inputForm.modelId,
            modelName: this.inputForm.modelName,
            companyName: this.inputForm.companyName,
            companyId: this.inputForm.companyId,
            dataType: this.inputForm.dataType,
            product: product,
            quantity: this.inputForm.quantity,
            smoney: this.inputForm.smoney,
            executeStartDate: this.sendDate[0],
            executeEndDate: this.sendDate[1],
            loss: {
              computeMethod: this.inputForm.computeMethod,
              allowLossQuantity: this.inputForm.allowLossQuantity,
              allowLossPercent: this.inputForm.allowLossPercent,
              randomUpper: this.inputForm.randomUpper,
              randomLower: this.inputForm.randomLower
            },
            contractCode: this.inputForm.contractCode,
            account: this.inputForm.account,
            remark: this.inputForm.remark,
            contractFileId: this.contractFileIdArr
          }
          postModelPage(params).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              Object.assign(this.$data, this.$options.data())

              this.jump()
            }
          })
        }
      })
    },
    close() {
      this.$confirm('确定取消吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        this.$router.push({path: '/business/business/index'})
        // if (this.inputForm.id) {
        //   this.tabsCloseCurrentHandle('/form/template?id=' + this.inputForm.id)
        // } else {
          this.tabsCloseCurrentHandle('/form/template?title=' + this.inputForm.modelName + '&id=' + this.inputForm.modelId + '&previewMode=true&method=add')
        // }
      })
    },
    jump () {
      this.$router.push({path: '/business/business/index'})
      this.tabsCloseCurrentHandle('/form/template?title=' + this.inputForm.modelName + '&id=' + this.inputForm.modelId + '&previewMode=true&method=add')
    },
    tabsCloseCurrentHandle (tabName) {
      this.removeTabHandle(tabName || this.mainTabsActiveName)
    },
    // tabs, 删除tab
    removeTabHandle (tabName) {
      var obj = this.mainTabs.filter(item => item.fullPath === tabName)[0]
      var index = this.mainTabs.indexOf(obj)
      this.mainTabs = this.mainTabs.filter(item => item.fullPath !== tabName)
      // this.mainTabsActiveName = '/deliveryManage/index'
      this.saveLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/config.scss';
.wrapper{
  .panel {
    display: flex;
    width: 1214px;
    margin: 0 auto;
    padding: 0 30px;
    >.el-form-item{
      width: 44%;
    }
    .contact-container{
      width: 44%;
    }

    .el-input, .el-select {
      width: 370px !important;
    }
    ::v-deep.adjustPopper.el-autocomplete .el-input__inner{
      width: 370px !important;
    }
    .adjustDate.el-date-editor--daterange.el-input__inner {
      width: 370px !important;
    }

    .arrow {
      position: relative;

      > div {
        position: absolute;
        top: 50%;
        margin-top: -27px;
        width: 100%;

        p {
          font-size: 24px;
          font-family: Source Han Sans CN;
          font-weight: bold;
          color: #2D2D2D;
          height: 52px;
          line-height: 52px;
          text-align: center;
        }
      }

      .arrow_center {
        display: flex;
        width: 148px;
        margin: 0 auto;
      }

      .line {
        height: 6px;
        width: 131px;
        background: $--color-primary-liyu;
        display: inline-block;
      }

      .triangle {
        border-bottom: 17px solid $--color-primary-liyu;
        border-left: 12px solid transparent;
        width: 0;
        height: 0;
        transform: rotate(90deg);
        position: relative;
        top: -8px;
        left: 1px;
        display: inline-block;
      }
    }
  }
  .contact-container {
    display: flex;
    /*margin-left: 30px;*/
    /*>.el-form-item:first-child{*/
    /*  .el-form-item__label{*/
    /*    width: 111px !important;*/
    /*  }*/
    /*  .el-form-item__content{*/
    /*    margin-left: 111px !important;*/
    /*  }*/
    /*}*/
    .el-select {
      width: 180px !important;
    }

    .el-input {
      width: 180px !important;

      input {
        width: 180px;
        min-width: 180px !important;
      }
    }
    &.compute{
      .el-select {
        width: 120px !important;
      }
      .el-input {
        width: 240px !important;

        input {
          width: 240px;
          min-width: 240px !important;
        }
      }
    }
    .el-form-item:not(:first-child) {
      margin-left: 10px;
    }
  }
  ::v-deep .textareaAppend{
    .el-textarea__inner{
      resize: none;
      border: 1px solid #AAAAAA;
      border-radius: 4px;
      padding: 5px 10px;
      &::-webkit-input-placeholder {
        color: #999999;
      }
    }
  }
  ::v-deep .remark{
    margin: 0 auto;
    padding: 0 30px;
  }
  ::v-deep.random{
    display: flex;
    .el-input-number__increase{
      line-height: 15px !important;
    }
    .el-input-number--mini {
      width: 102px;
    }
  }
  .text_center {
    text-align: center;
    //position: fixed;
    //bottom: 0;
    //padding-bottom: 20px;
    //width: calc(100% - 252px);
    //background: #FFFFFF;
    //padding-top: 20px;
    //box-shadow: 0px 8px 40px 0px rgba(0, 38, 115, 0.08);
    .el-button {
      font-size: 20px !important;
      font-family: Source Han Sans CN;
      font-weight: 400;
      height: 48px;
    }

    .but_save {
      border: 1px solid $--color-primary-liyu !important;
      color: $--color-primary-liyu !important;
    }

    .but_save, .btn_cancel {
      //width: 168px;
    }

    .btn_next {
      //width: 442px;
    }
  }
}



</style>
